export enum listActionTypes{
    append,
    replace,
    remove
}
export class listAction<T>{ 
    type: listActionTypes
    target: T | null
    removeIndex: number
    replaceIndex: number
    /**使用时，target不使用传入null，两个数字型变量不使用传入-1 */
    constructor(type: listActionTypes, target: T | null = null, removeIndex: number = -1, replaceIndex: number = -1){
        this.type = type
        this.target = target
        this.removeIndex = removeIndex
        this.replaceIndex = replaceIndex
    }
}

const replaceAt = function<T>(arr: T[], index: number, item: T){
    var ret = [] as T[]
    for(var i = 0; i < arr.length; i++){
        ret.push(i == index ? item : arr[i])
    }
    return ret
}

const appendAt = function<T>(arr: T[], item: T){
    var ret = [] as T[]
    for(var i = 0; i < arr.length; i++){
        ret.push(arr[i])
    }
    ret.push(item)
    return ret
}

const removeAt = function<T>(arr: T[], index: number){
    var ret = [] as T[]
    for(var i = 0; i < arr.length; i++){
        if(i != index){
            ret.push(arr[i])
        }
    }
    return ret
}

export const listReducer = function<T>(arr: T[] , action: listAction<T>){
    switch(action.type){
        case listActionTypes.append:
            if(action.target == null){
                throw new Error("ATTEMPTING TO APPEND A NULL VALUE TO THE LIST")
            }
            return appendAt<T>(arr, action.target)
            break
        case listActionTypes.remove:
            return removeAt<T>(arr, action.removeIndex)
            break
        case listActionTypes.replace:
            if(action.target == null){
                throw new Error("ATTEMPTING TO REPLACE A MEMBER WITH NULL VALUE")
            }
            return replaceAt<T>(arr, action.replaceIndex, action.target)
            break
        default:
            throw new Error("ACTION DOES NOT EXIST.")
    }
}